package com.kd.dataIndex.main;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.kd.config.DefaultConfig;
import com.kd.data.transport.DataIndexThread;
import com.kd.data.transport.DirLock;
import com.kdtech.utils.FileUtils;

public class Main {

	private static final Logger logger=Logger.getLogger(DataIndexThread.class);	
	
	public static void main(String[] args) {
		
		final String host = DefaultConfig.SERVER_IP;
		final int port = DefaultConfig.PORT;
		final String dir = DefaultConfig.DIR;
		final int scanTime = DefaultConfig.SCAN_SECONDS;
		
		//load inside data file to index-server
		Thread dataIndex = new DataIndexThread(host, port, dir, scanTime);
		dataIndex.start();
		
		//here, use to delete some directory that is empty and before today
		Runnable scheduleDelete = new Runnable() {

			@Override
			public void run() {
				try {
					DirLock.getInstance().acquire();
					doDelete();
					DirLock.getInstance().release();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			public void doDelete() {
				Calendar scheduleTime = Calendar.getInstance();
				scheduleTime.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, 1, 0);
				Calendar toDay = Calendar.getInstance();
				String month = "0" + (toDay.get(Calendar.MONTH)+1);
				String day = "0" + toDay.get(Calendar.DAY_OF_MONTH);
				month = month.substring(month.length()-2, month.length());
				day = day.substring(day.length()-2, day.length());
				String toDayDir = toDay.get(Calendar.YEAR) + "_" + month + "_" + day;
				// per day at 1:00 am. to delete
				if(toDay.after(scheduleTime)) {
					List<String> children = new ArrayList<String>();
					FileUtils.getChildrenDir(dir, children);
					for(String child : children) {
						File file = new File(child);
						if(!toDayDir.equals(file.getName())) {
							if(!FileUtils.hasNormalFiles(child)) {
								logger.info("start to delete " + child);
								file.delete();
								logger.info("finish to delete " + child);
							}
						}
					}
					children.clear();
					children = null;
				}
			}
		};
		
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();  
        // 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间  
        service.scheduleAtFixedRate(scheduleDelete, 10, 60*60*1, TimeUnit.SECONDS);
	}
	
}
